<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/29
 * Time: 14:18
 */

namespace osc\admin\controller;

use osc\common\controller\AdminBase;
use think\Db;
use think\Request;
use osc\common\service\Excel;

class Free extends AdminBase
{
    protected function _initialize(){
        parent::_initialize();
        $this->assign('breadcrumb1','新自由合约');
        $this->assign('breadcrumb2','申请审核');
        $this->assign('breadcrumb3','初审');
        $this->assign('breadcrumb4','终审');
        $this->assign('breadcrumb16','合约列表');
    }

    /**
     * 合约申请列表
     * @return mixed
     */
    public function apply(){
        $map = [];
        $username = $this->request->param('username');
        $sub_date = $this->request->param('sub_date');
        if(!empty($username)){
            $map['a.username'] = $username;
        }
        if(!empty($sub_date)){
            $map["sub_date"] = $sub_date;
        }

        $list = Db::name('free_contract a,osc_member b')
            ->where('a.username=b.username')
            ->where($map)
            ->where('a.state=0')
            ->order('id asc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);

        //查询交易所
        $exchange = Db::name('exchange_house')->where('state',1)->select();

        $variety = Db::name('exchage_variety')->where('state',1)->select();
        //查询合约列表
        $sum1 = Db::name('free_contract a')->where($map)->where('a.state=0 and type=1')->sum('price');
        $sum2 = Db::name('free_contract a')->where($map)->where('a.state=0 and type=2')->sum('price');
        $sum3 = Db::name('free_contract a')->where($map)->where('a.state=0')->sum('money');

        $page = $list->render();
        $this->assign('variety',$variety);
        $this->assign('exchange',$exchange);
        $this->assign('list',$list);
        $this->assign('sum1',$sum1);
        $this->assign('sum2',$sum2);
        $this->assign('sum3',$sum3);
        $this->assign('page',$page);
        return $this->fetch();
    }

    /**
     * 合约列表
     * @return mixed
     */
    public function list_free(){
        $param = $this->request->param();
        $map = null;
        if(isset($param['user_name']))
        {
            $map['username'] = $param['user_name'];
        }

        if(isset($param['begin_day']) && isset($param['begin_day2']))
        {

            $map['begin_day'] = [['>',date('Y-m-d',strtotime($param['begin_day']."-1 day"))],['<',date('Y-m-d',strtotime($param['begin_day2']."+1 day"))]];
        }
        elseif(isset($param['begin_day']))
        {
            $map['begin_day'] = $param['begin_day'];
        }
        elseif(isset($param['begin_day2']))
        {
            $map['begin_day'] = $param['begin_day2'];
        }

        if(isset($param['end_day']) && isset($param['end_day2']))
        {
            $map['end_day'] = [['>',date('Y-m-d',strtotime($param['end_day']."-1 day"))],['<',date('Y-m-d',strtotime($param['end_day2']."+1 day"))]];
        }
        elseif(isset($param['end_day']))
        {
            $map['end_day'] = $param['end_day'];
        }
        elseif(isset($param['end_day2']))
        {
            $map['end_day'] = $param['end_day2'];
        }

        if(isset($param['exchange_id'])){
            $map['exchange'] = $param['exchange_id'];
        }
        if(isset($param['variety_id'])){
            $map['exchange_variety'] = $param['variety_id'];
        }
        if(isset($param['s_state'])){
            $map['s_state'] = $param['s_state'];
        }

//        echo'<pre>';print_r($map);exit;

        $list = Db::name('free_contract')
            ->where('state <> 5')
            ->where($map)
            ->order('id desc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);
        $page = $list->render();
        //查询交易所
        $exchange = Db::name('exchange_house')->where('state',1)->select();

        $variety = Db::name('exchage_variety')->where('state',1)->select();

        $b_num = Db::name('free_contract')->where($map)->where('state<>5')->sum('b_num');
        $b_price = Db::name('free_contract')->where($map)->where('state<>5')->sum('b_price');

        $s_num = Db::name('free_contract')->where($map)->where('state<>5')->sum('s_num');
        $s_price = Db::name('free_contract')->where($map)->where('state<>5')->sum('s_price');

        $sum1 = Db::name('free_contract')->where($map)->where('state<>5 and type=1')->sum('price');
        $sum2 = Db::name('free_contract')->where($map)->where('state<>5 and type=2')->sum('price');
        $sum3 = Db::name('free_contract')->where($map)->where('state<>5')->sum('money');

        $this->assign('sum1',$sum1);
        $this->assign('sum2',$sum2);
        $this->assign('sum3',$sum3);
        $this->assign('b_num',$b_num);
        $this->assign('b_price',$b_price);
        $this->assign('s_num',$s_num);
        $this->assign('s_price',$s_price);
        $this->assign('variety',$variety);
        $this->assign('exchange',$exchange);
        $this->assign('page',$page);
        $this->assign('list',$list);
        $this->assign('breadcrumb6','买入确认');
        return $this->fetch();
    }


    /**
     * 买入确认
     * @return mixed
     */
    public function confirm(){
        $param = $this->request->param();
        $map = null;
        if(isset($param['user_name'])){
            $map['a.username'] = $param['user_name'];
        }
        if(isset($param['begin_day'])){
            $map['a.begin_day'] = $param['begin_day'];
        }
        if(isset($param['end_day'])){
            $map['a.end_day'] = $param['end_day'];
        }

        $list = Db::name('free_contract a')
            ->where('state=1 and buy_state=0 b_state=1')
            ->where($map)
            ->field('a.begin_day,a.end_day,a.id,a.username,a.exchange,a.exchange_variety,a.b_num,a.b_price,a.s_num,a.s_price,a.money,a.price')
            ->order('id desc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);
        $page = $list->render();
        $this->assign('page',$page);
        $this->assign('list',$list);
        $this->assign('breadcrumb6','买入确认');
        return $this->fetch();
    }

    /**
     * 买入确认审批操作
     * @return mixed
     */
    public function confirm_info(){
        if($this->request->isPost()){

            $data = $this->request->param();
            if($data){

                //审核通过
                if($data['checked'] == 1){

                    $price = 0;
                    $num = 0;

                    //价格录入条件
                    $sell_b = [];
                    $total_b = [];
                    for($i = 0;$i < count($data['b_num']); $i++){
                        $total_b[$i] = $data['b_num'][$i] * $data['b_price'][$i];

                        $sell_b[$i] = [
                            'free_id' 	=> $data['id'],
                            'num'	=> $data['b_num'][$i],
                            'price'	=> $data['b_price'][$i],
                            'type'	=> 1,
                        ];

                        $price = $price + $data['b_num'][$i] * $data['b_price'][$i];
                        $num = $num + $data['b_num'][$i];
                    }

                    $da['b_price'] = $price;
                    $da['b_num'] = $num;
                    $da['buy_state'] =1;
                    $da['b_real_date'] = $data['b_real_date'];


                    $res = Db::name('free_contract')->where('id',$data['id'])->update($da);

                    //价格条件录入
                    $sell_entry = Db::name('free_contract_sell')->insertAll($sell_b);

                    if($sell_entry && $res){
                        //结算奖励
                        $free_info = Db::name('free_contract')->where('id',$data['id'])->find();
                        $this->bonus($free_info['username'],$free_info['price']);

                        $this->redirect('free/confirm');
                    }else{
                        $this->error('确认失败');
                    }
                }
                //审核不通过
                if($data['checked'] == 2){
                    if($data['b_desc']){
                        $re = [
                            'free_id' 	  => $data['id'],
                            'remark'      => $data['b_desc'],
                            'type'        => 1,
                        ];

                        //录入审核意见
                        Db::name('free_contract_remark')->insert($re);
                    }

                    $res = Db::name('free_contract')->where('id',$data['id'])->update(['buy_state'=>2,'b_state'=>4,'state'=>4]);

                    if($res){

                        //发送短信
                        $apply = Db::name('free_contract')->where('id',$data['id'])->field('username')->find();
                        $r= osc_service('common','Rang')->sendsms_normal($apply['username']);

                        $this->redirect('free/confirm');
                    }else{
                        $this->error('打回失败');
                    }

                }

            }else{
                $this->error('提交错误');
            }
        }else{
            $id = $this->request->param('id');
            $info = Db::name('free_contract a')
                ->where('a.id',$id)
                ->field('a.*')
                ->order('id desc')
                ->find();
            $img = Db::name('free_contract_img')->where(['free_id'=>$id,'seq_id'=>1])->find();
            $b_img = Db::name('free_contract_img')->where(['free_id'=>$id,'seq_id'=>1])->select();
            //var_dump($id);
            $this->assign('info',$info);
            $this->assign('img',$img);
            $this->assign('b_img',$b_img);
            $this->assign('crumbs','买入确认审批');
            return $this->fetch();
        }

    }



    /*
    生成合约
    */

    public function create()
    {
        $param=input('param.');

        //获取合约类型
        //对参数进行校验
        if(!isset($param['exchange_id']))
        {
            $this->error('请输入交易所信息');
        }

        if(!isset($param['variety_id']))
        {
            $this->error('请输入交易品种');
        }


        if(!isset($param['all']))
        {
            $this->error('请选择要审批的合约');
        }

        if($param['exchange_id']=="")
        {
            $this->error('请输入交易所信息');
        }

        if($param['variety_id']=="")
        {
            $this->error('请输入交易品种');
        }

        if($param['all']=="")
        {
            $this->error('请选择要审批的合约');
        }


        $exchange_id = $param['exchange_id'];
        $variety_id = $param['variety_id'];
        //获取交易所信息
        $all = $param['all'];
        //获取排单编号

        //循环处理订单
        //获取
        foreach($all as $value)
        {
            //获取申请信息
            $free_info = Db::name('free_contract')->where('id',$value)->find();


            //设置合约信息
            $free['exchange'] = $exchange_id;
            $free['exchange_variety'] = $variety_id;

            //合约生效时间

            //获取今天的日期
            $begin_day = date("Y-m-d",strtotime("+1 day"));

            $begin_week = date("w",strtotime($begin_day));
            if($begin_week == 0)
            {
                $begin_day = date("Y-m-d",strtotime("+2 day"));
            }

            if($begin_week == 6)
            {
                $begin_day = date("Y-m-d",strtotime("+3 day"));
            }


            //节假日处理
            $begin_day = $this->is_holiday($begin_day);


            //周期类型为天
            $end_day = $begin_day;

            for ($x=1; $x<10; $x++)
            {
                //var_dump($end_day);

                $end_day = $this->getnextday($end_day);
            }

            //判断当天是否是星期六，星期天
            $end_week = date("w",strtotime($end_day));

            //星期天，延后一天
            if($end_week == 0)
            {
                $end_day = date("Y-m-d",strtotime("+2 day"));
            }

            if($end_week == 6)
            {
                $end_day = date("Y-m-d",strtotime("+3 day"));
            }


            //节假日处理
            $end_day = $this->is_holiday($end_day);

            $free['begin_day'] = $begin_day;
            $free['end_day'] = $end_day;
            $free['b_end_date'] = $begin_day;
            $free['s_end_date'] = $end_day;
            $free['state'] = 1;

            Db::name('free_contract')->where('id',$value)->update($free);

            $map = [
                'free_id'   => $free_info['id'],
                'desc'      => '合约生成批审通过',
                'operator'  => get_admin_user_name(UID),
                'state'     => 0,
                'type'      => 0
            ];

            Db::name('free_contract_desc')->insert($map);


            //发送短信
            $r= osc_service('common','Rang')->sendsms_contract($free_info['username']);

            //更新用户的级别
            $user = Db::name('member')->where('username',$free_info['username'])->find();
            if($user['user_state']==0)
            {
                Db::name('member')->where('username',$free_info['username'])->setInc('user_state',1);
            }

        }
        //die;
        $this->redirect('apply');
    }


    /**
     * 初审列表
     * @return mixed
     */
    public function first_list(){
        $param = $this->request->param();
        $map = null;
        if(isset($param['user_name'])){
            $map['username'] = $param['user_name'];
        }
        if(isset($param['begin_day'])){
            $map['begin_day'] = $param['begin_day'];
        }
        if(isset($param['end_day'])){
            $map['end_day'] = $param['end_day'];
        }
        if(isset($param['exchange_id'])){
            $map['exchange'] = $param['exchange_id'];
        }
        if(isset($param['variety_id'])){
            $map['exchange_variety'] = $param['variety_id'];
        }

        $list = Db::name('free_contract')
            ->where('state=2')
            ->where($map)
            ->order('s_state desc,id desc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);
        $page = $list->render();

        $exchange = Db::name('exchange_house')->where('state',1)->select();

        $variety = Db::name('exchage_variety')->where('state',1)->select();

        $this->assign('variety',$variety);
        $this->assign('exchange',$exchange);
        $this->assign('page',$page);
        $this->assign('list',$list);
        return $this->fetch();
    }


    /**
     * 终审列表
     * @return mixed
     */
    public function end_list(){
        $param = $this->request->param();
        $map = null;
        if(isset($param['user_name'])){
            $map['username'] = $param['user_name'];
        }
        if(isset($param['begin_day'])){
            $map['begin_day'] = $param['begin_day'];
        }
        if(isset($param['end_day'])){
            $map['end_day'] = $param['end_day'];
        }
        if(isset($param['exchange_id'])){
            $map['exchange'] = $param['exchange_id'];
        }
        if(isset($param['variety_id'])){
            $map['exchange_variety'] = $param['variety_id'];
        }
        $list = Db::name('free_contract')
            ->where('state=3')
            ->where($map)
            ->order('s_state desc,id desc')
            ->paginate(10,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);
        $page = $list->render();

        $exchange = Db::name('exchange_house')->where('state',1)->select();

        $variety = Db::name('exchage_variety')->where('state',1)->select();

        $this->assign('variety',$variety);
        $this->assign('exchange',$exchange);
        $this->assign('page',$page);
        $this->assign('list',$list);
        return $this->fetch();
    }


    /**
     * 合约初审
     * @return mixed
     */
    public function first_info(){
        if($this->request->isPost()){
            $param = $this->request->post();
            /**
             * 审核不通过
             */
            if($param['b_checked'] == 2 || $param['s_checked'] == 2){

                if($param['id'] == '' or $param['id'] == null){ $this->error('提交错误'); }

                /**
                 * 录入条件
                 */
                $co = [];
                $de = [];

                if($param['b_checked'] == 2){
                    $co['b_state'] = 4;

                    $de[] = [
                        'free_id' => $param['id'],
                        'desc'        => $param['b_desc'].'--买入',
                        'operator'    => get_admin_user_name(UID),
                        'state'       => 1,
                        'type'        => 1,
                    ];

                    $repulse['type'] = 1;
                    $repulse['remark'] = $param['b_desc'];
                }
                if($param['s_checked'] == 2){
                    $co['s_state'] = 4;

                    $de[] = [
                        'free_id' => $param['id'],
                        'desc'        => $param['s_desc'].'--卖出',
                        'operator'    => get_admin_user_name(UID),
                        'state'       => 1,
                        'type'        => 1,
                    ];

                    $repulse['type'] = 2;
                    $repulse['remark'] = $param['s_desc'];
                }

                $co['state'] = 4;

                $repulse['free_id']          =$param['id'];
                $repulse['free_state']       = 1;
                $repulse['operator']         = get_admin_user_name(UID);

                /**
                 * 条件录入
                 */

                $desc = Db::name('free_contract_desc')->insertAll($de);
                $free_repulse = Db::name('free_contract_remark')->insert($repulse);
                $free = Db::name('free_contract')->where('id',$param['id'])->update($co);

                if($desc && $free_repulse && $free){

                    //发送短信
                    $apply = Db::name('free_contract')->where('id',$param['id'])->field('username')->find();
                    $r= osc_service('common','Rang')->sendsms_normal($apply['username']);

                    $this->redirect('free/first_info');
                }else{
                    $this->error('操作失败');
                }
            }

            /**
             * 判断条件
             */
            if($param['id'] == '' or $param['id'] == null){ $this->error('提交错误'); }


            //查询订单用作对比
            $sell_condition = Db::name('free_contract_sell')->where(['free_id'=>$param['id'],'type'=>2])->count();

            if($sell_condition > 0){ $this->error('不能重复提交卖出交易情况'); }


            //判断提货
            if($param['s_real_date'] == '' or $param['s_real_date'] == null){ $this->error('卖出时间未填写'); }


            /**
             * 定义修改条件
             */

            //订单条件
            $map['id']          = $param['id'];
            $map['s_real_date'] = $param['s_real_date'];
            $map['b_state']     = 2;
            $map['s_state']     = 2;
            $map['state']       = 3;

            //审核意见条件
            $re = [];

            if($param['b_desc']){
                $re[] = [
                    'free_id' => $param['id'],
                    'remark'      => $param['b_desc'],
                    'type'        => 1,
                ];
            }
            if($param['s_desc']){
                $re[] = [
                    'free_id' => $param['id'],
                    'remark'      => $param['s_desc'],
                    'type'        => 2,
                ];
            }

            //操作记录条件
            $desc_checked = [
                [
                    'free_id' => $param['id'],
                    'desc'        => $param['b_desc'].'--买入',
                    'operator'    => get_admin_user_name(UID),
                    'state'       => 0,
                    'type'        => 1
                ],
                [
                    'free_id' => $param['id'],
                    'desc'        => $param['s_desc'].'--卖出',
                    'operator'    => get_admin_user_name(UID),
                    'state'       => 0,
                    'type'        => 1
                ]
            ];
            //价格录入条件
            $sell_s = [];
            $total_s = [];
            for($i = 0;$i < count($param['s_num']); $i++){
                $total_s[$i] = $param['s_num'][$i] * $param['s_price'][$i];
                $sell_s[$i] = [
                    'free_id'   => $param['id'],
                    'num'   => $param['s_num'][$i],
                    'price' => $param['s_price'][$i],
                    'type'  => 2,
                ];
            }

            $sell_b = [];
            $total_b = [];
            if(!empty($param['b_num'][0])){

                for($i = 0;$i < count($param['b_num']); $i++){
                    $total_b[$i] = $param['b_num'][$i] * $param['b_price'][$i];

                    $sell_b[$i] = [
                        'free_id'   => $param['id'],
                        'num'   => $param['b_num'][$i],
                        'price' => $param['b_price'][$i],
                        'type'  => 1,
                    ];
                }

                $map['b_num'] = array_sum($param['b_num']);
                $map['b_price'] = array_sum($total_b);

                Db::name('free_contract_sell')->where(['free_id'=>$param['id']])->delete();
            }

            $sell = array_merge($sell_b,$sell_s);

            $map['s_num'] = array_sum($param['s_num']);
            $map['s_price'] = array_sum($total_s);

            /**
             * 对定义条件录入
             */

            //录入订单
            $contract_entry = Db::name('free_contract')->where('id',$param['id'])->update($map);
            //录入审核意见
            $remark_entry = Db::name('free_contract_remark')->insertAll($re);
            //价格条件录入
            $sell_entry = Db::name('free_contract_sell')->insertAll($sell);
            //操作记录条件录入
            $desc_entry = Db::name('free_contract_desc')->insertAll($desc_checked);

            if($contract_entry  && $sell_entry && $desc_entry){
                $this->redirect('free/first_list');
            }else{
                $this->error('操作失败');
            }

        }else{
            $id = $this->request->get('id');

            $info = Db::name('free_contract')->where('id',$id)->find();

            $b_sell = Db::name('free_contract_sell')->where(['free_id'=>$id,'type'=>1])->select();

            $b_img = Db::name('free_contract_img')->where(['seq_id'=>1,'free_id'=>$id])->select();
            $s_img = Db::name('free_contract_img')->where(['seq_id'=>2,'free_id'=>$id])->select();

            $this->assign('info',$info);
            $this->assign('b_sell',$b_sell);
            $this->assign('b_img',$b_img);
            $this->assign('s_img',$s_img);
            $this->assign('crumbs','初审');
            return $this->fetch();
        }
    }

    /**
     * 终审
     * @return mixed
     */
    public function end_info(){
        if($this->request->isPost()){
            $param = $this->request->post();
            //结束合约
            if($param['checked'] == 4){
                $res = Db::name('free_contract')->where('id',$param['id'])->update(['state'=>5]);
                if ($res) {
                    $this->redirect('free/end_list');
                } else {
                    $this->error('操作失败');
                }
            }

            //审核通过
            if($param['checked'] == 1){
                $map['state'] = 5;
                $map['b_state'] = 3;
                $map['s_state'] = 3;

                $desc_checked = [
                    [
                        'free_id' => $param['id'],
                        'desc'        => $param['b_desc'].'--买入',
                        'operator'    => get_admin_user_name(UID),
                        'state'       => 1,
                        'type'        => 2
                    ],
                    [
                        'free_id' => $param['id'],
                        'desc'        => $param['s_desc'].'--卖出',
                        'operator'    => get_admin_user_name(UID),
                        'state'       => 1,
                        'type'        => 2
                    ]
                ];

                //查询订单信息
                $free = Db::name('free_contract')->where('id',$param['id'])->find();

                if($free['s_price'] !== null || $free['s_price'] !== 0 ){

                    if($free['b_price'] < $free['money'])
                    {
                        $quota = $free['b_price']*1.3 - $free['s_price'];
                    }
                    else
                    {
                        $quota = $free['money']*1.3 - $free['s_price'];
                    }


                    if($quota > 0){

                        //收益增补条件
                        $inc = [
                            'contract_id'   =>  $param['id'],
                            'username'      =>  $free['username'],
                            'exchange_id'   =>  $free['exchange'],
                            'variety_id'    =>  $free['exchange_variety'],
                            'inc'           =>  $quota,
                            'dt'            =>  time(),
                            'state'         =>  1,
                            'type_state'	=>  1,
                            'type'          =>  2
                        ];

                        //录入增补收益
                        Db::name('contract_increase')->insert($inc);
                        //转金豆
                        Db::name('member')->where('username',$free['username'])->setInc('predeposit',$quota);
                    }
                }

                //录入订单
                $contract_entry = Db::name('free_contract')->where('id',$param['id'])->update($map);
                //操作记录条件录入
                $desc_entry = Db::name('free_contract_desc')->insertAll($desc_checked);

                if($contract_entry && $desc_entry){
                    //修改用户新vip状态
                    $user = Db::name('member')->where('username',$free['username'])->find();
                    $mad = [];
                    if($user['vip_state'] != 1){
                        $mad['vip_state'] = 1;
                    }

                    if($user['user_state'] == 0){
                        $mad['user_state'] = 1;
                    }

                    Db::name('member')->where('username',$free['username'])->update($mad);

                    $this->redirect('free/end_list');

                }else{
                    $this->error('操作失败');
                }
            }

            //审核不通过
            if($param['checked'] == 2) {

                $map['state'] = 4;
                $map['b_state'] = 4;
                $map['s_state'] = 4;

                $desc_checked = [

                    [
                        'contract_id' => $param['id'],
                        'desc' => $param['b_desc'].'--买入',
                        'operator' => get_admin_user_name(UID),
                        'state' => 0,
                        'type' => 2
                    ],
                    [
                        'contract_id'   => $param['id'],
                        'desc'          => $param['s_desc'].'--卖出',
                        'operator'      => get_admin_user_name(UID),
                        'state'         => 0,
                        'type'          => 2
                    ]
                ];

                //录入订单
                $contract_entry = Db::name('free_contract')->where('id', $param['id'])->update($map);
                //操作记录条件录入
                $desc_entry = Db::name('free_contract_desc')->insertAll($desc_checked);
                //删除买入卖出记录
                $s_sell = Db::name('free_contract_sell')->where(['free_id'=>$param['id']])->delete();

                if ($contract_entry && $desc_entry && $s_sell) {

                    //发送短信
                    $apply = Db::name('free_contract')->where('id',$param['id'])->field('username')->find();
                    $r= osc_service('common','Rang')->sendsms_normal($apply['username']);

                    $this->redirect('free/end_list');
                } else {
                    $this->error('操作失败');
                }
            }
            //打回初审
            if($param['checked'] == 3) {
                $map['state'] = 2;
                $map['b_state'] = 2;
                $map['s_state'] = 2;

                $desc_checked = [

                    [
                        'free_id' => $param['id'],
                        'desc' => $param['b_desc'].'--买入',
                        'operator' => get_admin_user_name(UID),
                        'state' => 3,
                        'type' => 2
                    ],
                    [
                        'free_id' => $param['id'],
                        'desc' => $param['s_desc'].'--卖出',
                        'operator' => get_admin_user_name(UID),
                        'state' => 3,
                        'type' => 2
                    ]
                ];

                //录入订单
                $contract_entry = Db::name('free_contract')->where('id', $param['id'])->update($map);
                //操作记录条件录入
                $desc_entry = Db::name('free_contract_desc')->insertAll($desc_checked);
                //删除买入卖出记录
                Db::name('free_contract_sell')->where(['free_id'=>$param['id']])->delete();

                if ($contract_entry && $desc_entry ) {
                    $this->redirect('free/end_list');
                } else {
                    $this->error('操作失败');
                }
            }

        }else{
            $id = $this->request->get('id');
            $info = Db::name('free_contract')->where('id',$id)->find();
            //凭证图片
            $b_img = Db::name('free_contract_img')->where(['seq_id'=>1,'free_id'=>$id])->select();
            $s_img = Db::name('free_contract_img')->where(['seq_id'=>2,'free_id'=>$id])->select();

            //录入价格
            $b_sell = Db::name('free_contract_sell')->where(['type'=>1,'free_id'=>$id])->select();
            $s_sell = Db::name('free_contract_sell')->where(['type'=>2,'free_id'=>$id])->select();
//            print_r($b_sell);
//            print_r($s_sell);exit;
            $this->assign('info',$info);
            $this->assign('b_img',$b_img);
            $this->assign('s_img',$s_img);
            $this->assign('b_sell',$b_sell);
            $this->assign('s_sell',$s_sell);
            $this->assign('crumbs','终审');
            return $this->fetch();
        }
    }


    /**
     * ++++++++++++++++++++++++++++++++++++++++++++++++++
     * ++++++++++++++++++++++++++++++++++++++++++++++++++
     */


    /**
     * 导出新自由买卖
     * @throws \think\Exception
     */
    public function export_carried()
    {

        $param = $this->request->param();

        $map = null;
        if(isset($param['user_name']))
        {
            $map['a.username'] = $param['user_name'];
        }

        if(isset($param['begin_day']) && isset($param['begin_day2']))
        {

            $map['a.begin_day'] = [['>',date('Y-m-d',strtotime($param['begin_day']."-1 day"))],['<',date('Y-m-d',strtotime($param['begin_day2']."+1 day"))]];
        }
        elseif(isset($param['begin_day']))
        {
            $map['a.begin_day'] = $param['begin_day'];
        }
        elseif(isset($param['begin_day2']))
        {
            $map['a.begin_day'] = $param['begin_day2'];
        }

        if(isset($param['end_day']) && isset($param['end_day2']))
        {
            $map['a.end_day'] = [['>',date('Y-m-d',strtotime($param['end_day']."-1 day"))],['<',date('Y-m-d',strtotime($param['end_day2']."+1 day"))]];
        }
        elseif(isset($param['end_day']))
        {
            $map['a.end_day'] = $param['end_day'];
        }
        elseif(isset($param['end_day2']))
        {
            $map['a.end_day'] = $param['end_day2'];
        }

        if(isset($param['exchange_id'])){
            $map['a.exchange'] = $param['exchange_id'];
        }
        if(isset($param['variety_id'])){
            $map['a.exchange_variety'] = $param['variety_id'];
        }

        $excel=new Excel();

        $field = [
            "a.id"                  =>"序号",
            "a.username"            =>"用户",
            "b.idcardname"          =>"姓名",
            "a.begin_day"           =>"合约开始时间",
            "a.end_day"             =>"合约结束时间",
            "a.exchange"            =>"交易所",
            "a.exchange_variety"    =>"交易品种",
            "a.money"               =>"申请金额",
            "a.price"               =>"抵扣金额",
            "a.type"                =>"抵扣方式",
            "a.b_num"               =>"买入枚数",
            "a.b_price"             =>"买入价格",
            "a.s_num"               =>"卖出枚数",
            "a.s_price"             =>"卖出价格"
        ];

        $list = Db::name('free_contract a,osc_member b')
            ->where($map)
            ->where('a.state<>5 and a.username=b.username')
            ->field($field)
            ->order('a.s_state desc,a.id')
            ->select();

        foreach($list as $key=>&$value){
            $value['交易所账号'] = get_trade_id($value['用户'],$value['交易所']);
            $value['交易所'] = get_trade_name($value['交易所']);
            $value['交易品种'] = get_variety_name($value['交易品种']);
            if($value['抵扣方式'] == 1){
                $value['抵扣方式'] = '金豆';
            }else{
                $value['抵扣方式'] = '元宝';
            }

        }
        $field['a.acc'] = '交易所账号';
        $ft = "新自由买卖".date("Y-m-d",time());
//         echo"<pre>";print_r($list);
//         echo"<pre>";print_r($field);exit;
        $excel->setExcelName($ft)
            ->createSheetByList("新自由买卖",$list,$field)
            ->downloadExcel();
    }

    /**
     * 核算收益
     * @param $username
     * @param $money_id
     */
    function bonus($username,$money)
    {

        $ticket = $money*0.1;
        $ticket_sec = $money*0.05;
        $agent_ticket = $money*0.02;
        $area_ticket = $money*0.02;
        $agent_manage_ticket = $money*0.01;

        $bonus['con'] = '1';


        //给推荐人奖励
        $user = Db::name('member')->where('username',$username)->find();
        Db::name('member')->where('username',$user['sharemobile'])->setInc('predeposit',$ticket);
        $bonus['to_username'] = $username;
        $bonus['username'] = $user['sharemobile'];
        $bonus['num'] = $ticket;
        $bonus['type'] = 0;
        $bonus['create_time'] = time();
        $bonus['remark'] = '推荐';

        var_dump($bonus);


        Db::name('bonus')->insert($bonus);
        //给管理奖励

        //获取推荐人的推荐人
        $share = Db::name('member')->where('username',$user['sharemobile'])->find();
        $share1 = $share['sharemobile'];
        $s1count = Db::name('member')->where('sharemobile',$share1)->where('user_state > 0')->count();
        //$s1count = 5;
        if($s1count>=5)
        {
            Db::name('member')->where('username',$share1)->setInc('predeposit',$ticket_sec);
            $bonus_share1['to_username'] = $username;
            $bonus_share1['username'] = $share1;
            $bonus_share1['num'] = $ticket_sec;
            $bonus_share1['type'] = 0;
            $bonus_share1['create_time'] = time();
            $bonus_share1['remark'] = '推荐';
            $bonus_share1['con'] = '1';
            Db::name('bonus')->insert($bonus_share1);
        }


        //给区域代理奖励
        $area_team = Db::name('agent_area')->where('id6',$user['id6'])->find();
        if($area_team)
        {
            Db::name('member')->where('username',$area_team['username'])->setInc('predeposit',$area_ticket);
            $bonus_area['to_username'] = $username;
            $bonus_area['username'] = $area_team['username'];
            $bonus_area['num'] = $area_ticket;
            $bonus_area['type'] = 1;
            $bonus_area['create_time'] = time();
            $bonus_area['remark'] = '代理区域';
            $bonus_area['con'] = '1';
            Db::name('bonus')->insert($bonus_area);
        }


        //给团队代理奖励
        $team = $this->getshareagent($username);


        if($team)
        {
            Db::name('member')->where('username',$team)->setInc('predeposit',$agent_ticket);
            $bonus_team['to_username'] = $username;
            $bonus_team['username'] = $team;
            $bonus_team['num'] = $agent_ticket;
            $bonus_team['type'] = 1;
            $bonus_team['create_time'] = time();
            $bonus_team['remark'] = '代理团队';
            $bonus_team['con'] = '1';
            Db::name('bonus')->insert($bonus_team);
            var_dump($bonus_team);
        }


        //给代理的代理奖励
        $shareagent = $this->getshareagent($team);
        if($shareagent)
        {
            Db::name('member')->where('username',$shareagent)->setInc('predeposit',$agent_manage_ticket);
            $bonus_team2['to_username'] = $username;
            $bonus_team2['username'] = $shareagent;
            $bonus_team2['num'] = $agent_manage_ticket;
            $bonus_team2['type'] = 1;
            $bonus_team2['create_time'] = time();
            $bonus_team2['remark'] = '代理发展';
            $bonus_team2['con'] = '1';
            Db::name('bonus')->insert($bonus_team2);
            var_dump($bonus_team2);
        }


    }

    function getnextday($day)
    {

        //获取今天的日期

        $begin_day = date("Y-m-d",strtotime($day)+24*3600);
        //var_dump($begin_day);

        $begin_week = date("w",strtotime($begin_day));
        if($begin_week == 0)
        {
            $begin_day = date("Y-m-d",strtotime($day)+2*24*3600);
        }

        if($begin_week == 6)
        {
            $begin_day = date("Y-m-d",strtotime($day)+3*24*3600);
        }

        $begin_day = $this->is_holiday($begin_day);
        return $begin_day;

    }

    /**
     * 递归查询上级代理
     * @param $username
     * @return mixed|null
     */
    function getshareagent($username)
    {

        if(!$username)
        {
            return null;
        }
        $user = Db::name('member')->where('username',$username)->find();

        $shareuser = Db::name('member')->where('username',$user['sharemobile'])->where('user_state>1')->find();
        $agent = Db::name('agent')->where('username',$user['sharemobile'])->where('state=1 or state = 0')->find();


        if($agent)
        {

            return $shareuser['username'];

        }else
        {

            return $this->getshareagent($user['sharemobile']);

        }

    }



    function is_holiday($day)
    {
        $holiday = Db::name('holiday')->where('date_dt',$day)->find();
        if($holiday)
        {
            $day = date("Y-m-d",strtotime($day."+1 day"));
            $ret = $this->is_holiday($day);
            return $ret;
        }
        return $day;
    }


    /**
     * 根据时间和品种获取收盘价
     * @return array
     */
    function get_time_value(){
        if($this->request->isAjax()){
            $param = $this->request->param();

            $param['time'] = date("Y-m-d",strtotime("-1 day",strtotime($param['time'])));

            $res = Db::name('value_config')->where(['dt'=>$param['time'],'variety_id'=>$param['variety']])->find();

            if($res){
                return ['code'=>1,'msg'=>'OK','data'=>$res['rate']];
            }else{
                return ['code'=>0,'msg'=>'未设置收盘价','data'=>false];
            }
        }else{
            return ['code'=>-1,'msg'=>'获取失败','data'=>false];
        }
    }


    /**
     * 图片上传
     * @return int|string   array   返回值
     */
    public function do_upload(){
        if($this->request->isPost()) {
            $data = $this->request->param();
            $files = request()->file('image');
            $id = $data['id'];
            $info = "";
            $map = null;
            foreach ($files as $key => $picFile) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $picFile
                    ->move(ROOT_PATH . '/public/uploads/images');
                /*获取存储路径，以便插入数据库*/
                $map[$key]['img_path'] = "/public/uploads/images/" . $info->getSaveName();
                $map[$key]['file_name'] = $info->getFilename();
                $map[$key]['free_id'] = $id;
                $map[$key]['seq_id'] = $data['seq_id'];
            }
            $img = Db::name('free_contract_img')->insertAll($map);

            if ($info !== "" && $img) {
                $this->redirect("free/first_list");
            } else {
                // 上传失败获取错误信息
                $this->error('上传失败');
            }
        }
        $info = $this->request->param();
//        print_r($data);exit;
        $this->assign('info',$info);
        $this->assign('crumbs','图片上传');
        return $this->fetch();
    }



}